﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace laohan.Common.Common
{
    public partial class API
    {
        /// <summary>
        /// 二进制数据转换成base64字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string BytesToBase64String(byte[] bytes)
        {
            return Convert.ToBase64String(bytes);
        }

        /// <summary>
        /// base64字符串转换成二进制数据
        /// </summary>
        /// <param name="strBase64String"></param>
        /// <returns></returns>
        public static byte[] Base64StringToBytes(string strBase64String)
        {
            return Convert.FromBase64String(strBase64String);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string FileToBase64(string filePath)
        {
            var bytes = GetFileBytes(filePath);

            return BytesToBase64String(bytes);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strBase64String"></param>
        /// <returns></returns>
        public static string Base64StringToString(string strBase64String)
        {
            var bytes = Base64StringToBytes(strBase64String);

            return ByteArrayToString(bytes);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="base64"></param>
        /// <returns></returns>
        public static Bitmap Base64ToBitmap(string base64)
        {
            var bytes = Base64StringToBytes(base64);

            return BytesToBitmap(bytes);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static Image Base64ToImage(string base64)
        {
            try
            {
                var bytes = Base64StringToBytes(base64);

                if (bytes == null || bytes.Length <= 0)
                {
                    return null;
                }

                MemoryStream ms = new MemoryStream(bytes);

                return Image.FromStream(ms);
            }
            catch (Exception ex)
            {
                throw new Exception("二进制数据转换成图像发生错误，错误原因：" + ex.Message);
            }
        }
    }
}
